package com.sevencar.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnSwipeListener;
import com.example.lightble.R;
import com.example.lightble.db.SettingDatabase;

public class SimpleActivity extends Activity {

	private List<ApplicationInfo> mAppList;
	private AppAdapter mAdapter;
	private SwipeMenuListView mListView;

	List<Map<String, String>> groupNameList = new ArrayList<Map<String,String>>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list);

		mAppList = getPackageManager().getInstalledApplications(0);

		mListView = (SwipeMenuListView) findViewById(R.id.listView);
		
		mAdapter = new AppAdapter();
		
		mListView.setAdapter(mAdapter);

		// step 1. create a MenuCreator
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "open" item
				SwipeMenuItem openItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
						0xCE)));
				// set item width
				openItem.setWidth(dp2px(90));
				// set item title
				openItem.setTitle("Open");
				// set item title fontsize
				openItem.setTitleSize(18);
				// set item title font color
				openItem.setTitleColor(Color.WHITE);
				// add to menu
//				menu.addMenuItem(openItem);

				// create "delete" item
				SwipeMenuItem deleteItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
						0x3F, 0x25)));
				// set item width
				deleteItem.setWidth(dp2px(90));
				// set a icon
				deleteItem.setIcon(R.drawable.ic_delete);
				// add to menu
				menu.addMenuItem(deleteItem);
			}
		};
		// set creator
		mListView.setMenuCreator(creator);

		// step 2. listener item click event
		mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public void onMenuItemClick(int position, SwipeMenu menu, final int index) {
//				ApplicationInfo item = mAppList.get(position);
				final String group_code = groupNameList.get(position).get("group_code");
				switch (index) {
				case 0:
					// open
//					open(item);
//					delete(item);
//					Toast.makeText(getApplicationContext(), position + "  delete click", 0).show();
					
					AlertDialog.Builder builder = new Builder(SimpleActivity.this);
					builder.setMessage("确定要删除吗？");
					builder.setTitle("提示");
					builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							
							SettingDatabase sdb = new SettingDatabase(SimpleActivity.this,0);
							
//							groupNameList=sdb.query_maplist("select  count(*) as count, group_code, group_name from table_group group by group_code ");
							sdb.execSQL("delete  from table_group  where group_code = '"+group_code+"' ");
							sdb.close();
							
							groupNameList.remove(index);
							mAdapter.notifyDataSetChanged();
//							mListView.ref
							
						}
					});
					builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
					 builder.create().show();
					
					break;
				case 1:
					// delete
//					delete(item);
					mAppList.remove(position);
					mAdapter.notifyDataSetChanged();
					break;
				}
			}
		});
		
		// set SwipeListener
		mListView.setOnSwipeListener(new OnSwipeListener() {
			
			@Override
			public void onSwipeStart(int position) {
				// swipe start
			}
			
			@Override
			public void onSwipeEnd(int position) {
				// swipe end
			}
		});
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
//				Toast.makeText(getApplicationContext(), position + "  click", 0).show();
				Intent ii = new Intent(SimpleActivity.this,LightGroupEditActivity.class);
				ii.putExtra("group_code", groupNameList.get(position).get("group_code"));
				ii.putExtra("group_name", groupNameList.get(position).get("group_name"));
				startActivity(ii);
				
			}
		});

		// other setting
//		listView.setCloseInterpolator(new BounceInterpolator());
		
		// test item long click
		mListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				Toast.makeText(getApplicationContext(), position + " long click", 0).show();
				return false;
			}
		});
		
		
		findViewById(R.id.id_light_group_add).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent ii = new Intent(SimpleActivity.this,LightGroupAddActivity.class);
				ii.putExtra("isEdit", false);
				startActivity(ii);
			}
		});
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		SettingDatabase sdb = new SettingDatabase(this,0);
		
		groupNameList=sdb.query_maplist("select  count(*) as count, group_code, group_name from table_group group by group_code ");
		sdb.close();
		
		mAdapter.notifyDataSetChanged();
		
		System.out.println("[size]--"+groupNameList.size());
		
		
	}

	private void delete(ApplicationInfo item) {
		// delete app
		try {
			Intent intent = new Intent(Intent.ACTION_DELETE);
			intent.setData(Uri.fromParts("package", item.packageName, null));
			startActivity(intent);
		} catch (Exception e) {
		}
	}

	private void open(ApplicationInfo item) {
		// open app
		Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
		resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		resolveIntent.setPackage(item.packageName);
		List<ResolveInfo> resolveInfoList = getPackageManager()
				.queryIntentActivities(resolveIntent, 0);
		if (resolveInfoList != null && resolveInfoList.size() > 0) {
			ResolveInfo resolveInfo = resolveInfoList.get(0);
			String activityPackageName = resolveInfo.activityInfo.packageName;
			String className = resolveInfo.activityInfo.name;

			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			ComponentName componentName = new ComponentName(
					activityPackageName, className);

			intent.setComponent(componentName);
			startActivity(intent);
		}
	}

	class AppAdapter extends BaseAdapter {
		
		
		

		@Override
		public int getCount() {
			return groupNameList.size();
		}

		@Override
		public Map<String, String> getItem(int position) {
			return groupNameList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(getApplicationContext(),
						R.layout.item_list_app, null);
				new ViewHolder(convertView);
			}
			ViewHolder holder = (ViewHolder) convertView.getTag();
			Map<String, String> item = getItem(position);
			holder.tv_con.setText("共有"+ item.get("count")+"个设备");
			holder.tv_name.setText("组名："+ item.get("group_name"));
			return convertView;
		}

		class ViewHolder {
			TextView tv_con;
			TextView tv_name;

			public ViewHolder(View view) {
				tv_con = (TextView) view.findViewById(R.id.tv_con);
				tv_name = (TextView) view.findViewById(R.id.tv_name);
				view.setTag(this);
			}
		}
	}

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}
	
	
	
}
